<?php
require_once 'header.php';

// 检查是否已登录
if (!isLoggedIn()) {
    $_SESSION['flash_message'] = '请先登录再添加商品到购物车';
    $_SESSION['flash_message_type'] = 'warning';
    header('Location: login.php');
    exit;
}

// 检查是否有POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;
    $quantity = isset($_POST['quantity']) ? (int)$_POST['quantity'] : 1;
    
    // 验证产品ID和数量
    if ($product_id <= 0) {
        $_SESSION['flash_message'] = '无效的商品ID';
        $_SESSION['flash_message_type'] = 'danger';
        header('Location: index.php');
        exit;
    }
    
    if ($quantity <= 0 || $quantity > 10) {
        $quantity = 1; // 默认数量为1
    }
    
    // 检查产品是否存在
    $product = getProduct($product_id);
    if (!$product) {
        $_SESSION['flash_message'] = '商品不存在';
        $_SESSION['flash_message_type'] = 'danger';
        header('Location: index.php');
        exit;
    }
    
    // 添加到购物车
    $user_id = $_SESSION['user_id'];
    $success = addToCart($user_id, $product_id, $quantity);
    
    if ($success) {
        $_SESSION['flash_message'] = '商品成功添加到购物车！';
        $_SESSION['flash_message_type'] = 'success';
    } else {
        $_SESSION['flash_message'] = '添加商品到购物车失败，请重试';
        $_SESSION['flash_message_type'] = 'danger';
    }
    
    // 重定向回商品页面或购物车
    $redirect_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'cart.php';
    header("Location: $redirect_url");
    exit;
} else {
    // 如果不是POST请求，重定向到首页
    header('Location: index.php');
    exit;
} 